package my.Imitation.writing;
/**
 * Created with IntelliJ IDEA.
 *
 * @Author: Tom
 * @Date: 2022/02/13/21:08
 * @Description:
 */

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

/**
 *@ClassName LRUCache1
 *@Description
 *@Author 王琛
 *@Date 2022/2/13 21:08
 @Version 1.0
 */
public class LRUCache1 {
    Map<Integer, Integer> map;
    int maxSize;
    public LRUCache1(int capacity) {
        map = new LinkedHashMap<>();
        maxSize = capacity;
    }

    public int get(int key) {
        if (map.containsKey(key)){
            int value = map.get(key);
            map.remove(key);
            map.put(key,value);
            return value;
        }
        return -1;
    }

    public void put(int key, int value) {
        if(map.containsKey(key)){
            map.remove(key);
        }else if(map.size() == maxSize){
            Iterator<Entry<Integer,Integer>> it = map.entrySet().iterator();
            it.next();
            it.remove();
        }
        map.put(key, value);
    }
}
